package com.fanhao.dllo.soundfm.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.fanhao.dllo.soundfm.R;
import com.fanhao.dllo.soundfm.entity.MainPlayEntity;
import com.fanhao.dllo.soundfm.entity.PlayActivityInforResult;
import com.fanhao.dllo.soundfm.entity.UiToServiceString;
import com.fanhao.dllo.soundfm.volley.GetBitmap;
import com.fanhao.dllo.soundfm.volley.VolleySingleton;
import com.google.gson.Gson;


import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 16/1/15.
 * 全局播放界面
 */
public class PlayActivity extends BaseActivity implements View.OnClickListener {

    private String uid;
    private ImageView bigPlayIv;
    private TextView titlePlayTv, albumPlayTv, anchorPlayTv;
    private ImageView backPlayIv, playLastIv, playNextIv, stopTv, playIv,
            commentPlayTv;
    private String musicUrl, urlFromMain;
    private SeekBar seekBar;
    private Bitmap bitmap;
    private MainPlayEntity mainPlayEntity = new MainPlayEntity();
    Handler handler;
    private int progress;

    @Override
    protected int setLayout() {
        return R.layout.activity_play;
    }

    @Override
    protected void initView() {
        commentPlayTv = findView(R.id.ivComment_playActivity);
        bigPlayIv = findView(R.id.ivBig_playActivity);
        albumPlayTv = findView(R.id.tvAlbum_playActivity);
        titlePlayTv = findView(R.id.tvTitle_playActivity);
        anchorPlayTv = findView(R.id.tvAnchor_playActivity);
        backPlayIv = findView(R.id.ivBack_playActivity);
        seekBar = findView(R.id.seekBar_playActivity);
        playLastIv = findView(R.id.ivPlayLeft_playActivity);
        playNextIv = findView(R.id.ivPlayRight_playActivity);
        stopTv = findView(R.id.ivStop_playActivity);
        playIv = findView(R.id.ivPlay_playActivity);

        commentPlayTv.setOnClickListener(this);
        stopTv.setOnClickListener(this);
        playIv.setOnClickListener(this);
        playLastIv.setOnClickListener(this);
        playNextIv.setOnClickListener(this);

        backPlayIv.setOnClickListener(this);
        seekBar.setEnabled(true);

        // 点击item后跳转的intent对象
        // 如果是item条转过来的 uid 就有值
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        uid = String.valueOf(bundle.getLong("trackId"));
        // 在这个方法中判断PlayActivity是
        // 从Mainactivity跳转过来的
        // 还是要进行网络请求的
        initSetPlayFromMain();
    }

    private void initSetPlayFromMain() {
        // Mainactivity跳转过来的intent对象
        // 如果是从Mainactivity跳转过来的,
        // 则 bmp,progress,max会有值
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        Bitmap bmp = bundle.getParcelable("mainPlayEntity");
        progress = bundle.getInt("progress");
        int max = bundle.getInt("max");

        // progress是Mainactivity跳转过来传的值
        if (progress > 0) {
            // progress > 0, 说明是该界面是从 Mainactivity跳转过来的
            // 给MusicService发送一个seekBar
            // 在musicService接收之后调用其自身的setSeekBar方法赋予一个可控的对象
            EventBus.getDefault().post(seekBar);
            // 将各种值设置上
            titlePlayTv.setText(intent.getStringExtra("title"));
            albumPlayTv.setText(intent.getStringExtra("minTitle"));
            GetBitmap.getBitmap(intent.getStringExtra("url"), bigPlayIv);

            // 日了,注了它也好使:应该是上方的EventBus搞的鬼
            // 通过handler里Thread子线程每隔一秒给handler发送一个消息,
            // 子线程中又发送一个eventsBus传给MusicService,让其设置seekBar
            // 再次激活handler,如此的一个死循环,就达到了seeBar的进度条不断刷新
//            handler = new Handler() {
//                @Override
//                public void handleMessage(Message msg) {
//                    super.handleMessage(msg);
//
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            try {
//                                Thread.sleep(1000);
//                               EventBus.getDefault().post(new UiToServiceString("", 5));
//                                handler.sendEmptyMessage(0);
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }).start();
//
//                }
//            };
//            handler.sendEmptyMessage(0);

        } else {
            initNetWork();
        }

    }

    private void initNetWork() {
        // 介绍部分url
        final String url = "http://mobile.ximalaya.com/mobile/track/" + uid + "?device=android";
        StringRequest request = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        PlayActivityInforResult result = gson.fromJson(response,
                                PlayActivityInforResult.class);
                        if (result != null) {
                            titlePlayTv.setText(result.getTitle() + "");
                            Log.d("PlayActivity", result.getTitle());
                            albumPlayTv.setText("《" + result.getAlbumTitle() + "》");
                            anchorPlayTv.setText(result.getNickname());
                            GetBitmap.getBitmap(result.getCoverLarge(), bigPlayIv);
                            musicUrl = result.getPlayUrl32();
                            // 通过传给MusicService信号来使其播放音乐
                            EventBus.getDefault().post(new UiToServiceString(musicUrl, 1));
                            EventBus.getDefault().post(seekBar);

                            mainPlayEntity.setUrl(result.getCoverLarge());
                            mainPlayEntity.setTitle(result.getTitle() + "");
                            mainPlayEntity.setAlbum("《" + result.getAlbumTitle() + "》");

                            ImageRequest request = new ImageRequest(result.getCoverLarge(),
                                    new Response.Listener<Bitmap>() {
                                        @Override
                                        public void onResponse(Bitmap response) {
                                            mainPlayEntity.setBitmap(response);
                                        }
                                    }, 700, 200, Bitmap.Config.ARGB_8888,
                                    new Response.ErrorListener() {
                                        @Override
                                        public void onErrorResponse(VolleyError error) {

                                        }
                                    });
                            VolleySingleton.getInstance().addRequest(request);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        VolleySingleton.getInstance().addRequest(request);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivPlayLeft_playActivity:

                break;
            case R.id.ivPlayRight_playActivity:

                break;
            case R.id.ivStop_playActivity:
                // 向musicService中发送一个 type = 2的UIToService类
                // 在musicService中判断type= 2 时,停止播放音乐
                EventBus.getDefault().post(new UiToServiceString("", 2));
                stopTv.setVisibility(View.INVISIBLE);
                playIv.setVisibility(View.VISIBLE);
                mainPlayEntity.setIsStop(true);
                break;
            case R.id.ivPlay_playActivity:
                // 向musicService中发送一个 type = 3的UIToService类
                // 在musicService中判断type= 3 时,继续播放音乐
                EventBus.getDefault().post(new UiToServiceString("", 3));
                playIv.setVisibility(View.GONE);
                stopTv.setVisibility(View.VISIBLE);
                mainPlayEntity.setIsStop(false);
                break;
            case R.id.ivBack_playActivity:
                // progress是MianActivity中传过来的值,
                // 通过判断progress来设置返回的效果
                if (progress > 0) {
                    // 从Mainactivity点击后进入的PlayActivity
                    finish();
                    overridePendingTransition(R.anim.no_move, R.anim.move_out_from_bottom);
                } else {
                    // 进行网络请求的PlayActivity
                    finish();
                    overridePendingTransition(R.anim.no_move, R.anim.move_out_from_bottom);
                    // 给mainActivity发送事件
                    // 将赋值好的mianPlayEntity类传给Mainactivity
                    EventBus.getDefault().post(mainPlayEntity);
                }
                break;
            case R.id.ivComment_playActivity:
                Intent intent = new Intent();
                intent.setClass(this, CommentActivity.class);
                intent.putExtra("uid", uid);
                startActivity(intent);
                overridePendingTransition(R.anim.move_in_from_right,R.anim.move_out_from_bottom);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


}
